package com.pinyougou.sellergoods.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pinyougou.mapper.TbBrandMapper;
import com.pinyougou.pojo.PageResult;
import com.pinyougou.pojo.TbBrand;
import com.pinyougou.pojo.TbBrandExample;
import com.pinyougou.sellergoods.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;


import java.util.List;

@Service
public class BrandServiceImpl implements BrandService {
    @Autowired
    private TbBrandMapper brandMapper;
    //1.查询所有品牌
    @Override
    public List<TbBrand> findAll() {
        return brandMapper.selectByExample(null);
    }

    //2.分页查询所有品牌
    @Override
    public PageResult findByPage(int page, int pagesize) {
        //1.开始分页查询
        PageHelper.startPage(page,pagesize);
        //2.查询出每页的记录集合
        TbBrandExample example = new TbBrandExample();
        List<TbBrand> tbBrands = brandMapper.selectByExample(example);
        //3.将品牌列表转换为分页对象
        Page<TbBrand> brandPage = (Page<TbBrand>) tbBrands;
        //4.将上面的brandPage转为PageResult对象并返回
        return new PageResult(brandPage.getTotal(),brandPage.getResult());
    }

    //3.分页待条件查询品牌列表
    @Override
    public PageResult search(int page, int pagesize, TbBrand brand) {
        //1.开始分页查询
        PageHelper.startPage(page,pagesize);
        //2.查询出每页的记录集合
        //2.1创建查询实例
        TbBrandExample example = new TbBrandExample();
        //2.2构造查询条件
        TbBrandExample.Criteria criteria = example.createCriteria();
        //2.3添加查询条件
        if (brand != null){
            if (!StringUtils.isEmpty(brand.getName())){
                criteria.andNameLike("%"+brand.getName()+"%");
            }
            if (!StringUtils.isEmpty(brand.getFirstChar())){
                criteria.andFirstCharEqualTo(brand.getFirstChar());
            }
        }
        //3.将品牌列表转换为分页对象
        List<TbBrand> tbBrands = brandMapper.selectByExample(example);
        Page<TbBrand> brandPage = (Page<TbBrand>) tbBrands;
        //4.将上面的brandPage转为PageResult对象并返回
        return new PageResult(brandPage.getTotal(),brandPage.getResult());
    }

    //4.添加品牌
    @Override
    public void add(TbBrand brand) {
        brandMapper.insert(brand);
    }

    //5.修改品牌
    @Override
    public void update(TbBrand brand) {
        brandMapper.updateByPrimaryKey(brand);
    }

    //6.根据用户选择的品牌id列表删除多个品牌
    @Override
    public void delete(String[] ids) {
        for (String id : ids) {
            brandMapper.deleteByPrimaryKey(Long.parseLong(id));
        }
    }
}
